﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json;
using System.Net.Http.Formatting;
using MxTol.API.Helpers;
using MxTol.Models;

namespace MxTol.API.Controllers
{
    /// <summary>
    /// 服务器方法功能控制器
    /// </summary>
    public class ServerController : ApiController
    {
        // 返回json数据格式
        private static readonly JsonMediaTypeFormatter JSON_FORMATTER = new JsonMediaTypeFormatter();

        // <summary>
        /// 获取服务器UTC标准时间
        /// </summary>
        [HttpGet]
        public HttpResponseMessage GetUtcTime()
        {
            string time = string.Empty;
            try
            {
                time = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch (Exception ex)
            {
                time = string.Empty;
                LogHelper.WriteLogAsync("客户端调用获取服务器UTC标准时间接口失败", ex);
            }

            Dictionary<string, string> json = new Dictionary<string, string>()
            {
                {"time",time},
            };

            return Request.CreateResponse(HttpStatusCode.OK, json, JSON_FORMATTER);
        }

        /// <summary>
        /// 客户端意见反馈
        /// </summary>
        [HttpPost]
        public HttpResponseMessage FeedBack()
        {
            // 0：服务器内部异常
            // 1: 安全码不正确
            // 2：成功
            
            int flag = 0;
            try
            {
                string key = WebQueryHelper.QueryFormString("key");
                string advice = WebQueryHelper.QueryFormString("advice");
                string contact = WebQueryHelper.QueryFormString("contact");

                if (SafeKeyHelper.VerifySafeKey(key))
                {
                    if (!string.IsNullOrEmpty(advice))
                    {
                        FeedBack back = new FeedBack();
                        back.Advice = advice;
                        back.Contact = contact;
                        back.AddTime = DateTime.Now;

                        back.Save();
                        flag = 2;
                    }
                }
                else
                {
                    flag = 1;
                }
            }
            catch (Exception ex)
            {
                flag = 0;
                LogHelper.WriteLogAsync("客户端调用意见反馈接口失败", ex);
            }

            Dictionary<string, int> json = new Dictionary<string, int>() { { "state", flag } };
            return Request.CreateResponse(HttpStatusCode.OK, json, JSON_FORMATTER);
        }
    }
}
